<template>
  <div class="warn-rule-container">
    <div
      v-for="(rule, ruleIndex) in warnRules"
      :key="rule.id"
      class="warn-rule-item"
    >
      <!-- 确保条件列表结构完整后再渲染 -->
      <div v-if="ensureConditionsStructure(rule)">
        <el-form :model="rule" label-width="120px" class="warn-form">
          <!-- 隐藏id但保留数据 -->
          <input type="hidden" :value="rule.id" />

          <el-form-item label="预警名称" prop="warnname">
            <el-input
              disabled
              v-model="rule.warnname"
              placeholder="请输入预警名称"
            ></el-input>
          </el-form-item>

          <el-form-item label="预警类型" prop="warntype">
            <el-select
              disabled
              style="width: 100%"
              v-model="rule.warntype"
              placeholder="请选择预警类型"
            >
              <el-option
                v-for="(type, typeIndex) in warnTypes"
                :key="typeIndex"
                :label="type.label"
                :value="type.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <!-- 动态条件项：根据busWaterWarnruleConditionsList中的每一项动态生成 -->
          <template
            v-for="(
              condition, condIndex
            ) in rule.busWaterWarnruleConditionsList"
          >
            <!-- 第一个条件项 -->
            <el-form-item
              v-if="condIndex === 0"
              :label="condition.conditionname || '条件名称'"
              :key="'cond-' + condIndex"
            >
              <el-input
                v-model="condition.numvalue"
                placeholder="请输入值"
                readonly
              ></el-input>
            </el-form-item>

            <!-- 第二个条件项 -->
            <el-form-item
              v-if="condIndex === 1"
              :label="condition.conditionname || '条件名称'"
              :key="'cond-' + condIndex"
            >
              <el-radio-group v-model="condition.numvalue">
                <el-radio :label="'1'">是</el-radio>
                <el-radio :label="'0'">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 第三个条件项 -->
            <el-form-item
              v-if="condIndex === 2"
              :label="condition.conditionname || '判断条件'"
              :key="'cond-' + condIndex"
            >
              <div class="judgment-condition">
                <!-- 条件名称使用当前条件项的conditionname -->
                <span>{{ condition.conditionname || "条件" }}</span>

                <!-- 第一个符号和值 -->
                <span v-if="condition.symbol">
                  {{ getSymbolText(condition.symbol) }}
                </span>
                <el-input
                  v-model="condition.numvalue"
                  placeholder="请输入条件值"
                  style="width: 80px; margin: 0 5px"
                ></el-input>

                <!-- 第二个符号和值（有值才显示） -->
                <template v-if="hasSecondCondition(condition)">
                  <span> 且 {{ getSymbolText(condition.symbol2) }} </span>
                  <el-input
                    v-model="condition.numvalue2"
                    placeholder="请输入条件值"
                    style="width: 80px; margin-left: 5px"
                  ></el-input>
                </template>
              </div>
            </el-form-item>
          </template>

          <el-form-item label="预警级别" prop="warnlevel">
            <el-select v-model="rule.warnlevel" placeholder="请选择预警级别">
              <el-option
                v-for="(level, levelIndex) in warnLevels"
                :key="levelIndex"
                :label="level.label"
                :value="level.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="预警描述" prop="warndesc">
            <el-input
              type="textarea"
              v-model="rule.warndesc"
              placeholder="请输入预警描述"
              :rows="3"
            ></el-input>
          </el-form-item>

          <el-form-item label="是否开启" prop="isno">
            <el-radio-group v-model="rule.isno">
              <el-radio :label="'0'">是</el-radio>
              <el-radio :label="'1'">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="updateRule(ruleIndex)"
              >更新</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import dayjs from "dayjs"; // 引入 day.js
import { getWarningRule, updateWarningRule } from "@/api/waterWarningAnalysis";
export default {
  data() {
    return {
      warnRules: [],
      warnTypes: [
        { label: "相关性预警", value: "1" },
        { label: "持续超标", value: "2" },
        { label: "限值预警", value: "3" },
        { label: "持续恶化", value: "4" },
        { label: "监测项超标", value: "5" },
        { label: "断面超标", value: "6" },
        { label: "瞬时突变", value: "7" },
        { label: "达标差距", value: "8" },
        { label: "站点离线", value: "9" },
      ],
      warnLevels: [
        { label: "一级", value: "1" },
        { label: "二级", value: "2" },
        { label: "三级", value: "3" },
      ],
      symbolMap: {
        1: "≥",
        2: ">",
        3: "≤",
        4: "<",
        5: "=",
      },
    };
  },
  created() {
    this.getWarningRule();
  },
  methods: {
    // 获取预警规则数据
    getWarningRule() {
      let params = {
        warntype: "102",
      };
      getWarningRule(params)
        .then((res) => {
          // 初始化数据并确保结构完整
          this.warnRules = (res.data || []).map((rule) => {
            this.ensureConditionsStructure(rule);
            return rule;
          });
        })
        .catch((err) => {
          console.error("获取规则数据失败:", err);
        });
    },

    // 确保条件列表结构完整，避免空指针
    ensureConditionsStructure(rule) {
      // 如果条件列表不存在，创建空数组
      if (!Array.isArray(rule.busWaterWarnruleConditionsList)) {
        this.$set(rule, "busWaterWarnruleConditionsList", []);
      }

      // 确保至少有3个条件对象
      for (let i = 0; i < 3; i++) {
        if (!rule.busWaterWarnruleConditionsList[i]) {
          this.$set(rule.busWaterWarnruleConditionsList, i, {
            conditionname: "", // 条件名称
            numvalue: "", // 数值1
            symbol: "", // 符号1
            symbol2: "", // 符号2
            numvalue2: "", // 数值2
          });
        } else {
          // 确保对象中的字段存在
          const fields = [
            "conditionname",
            "numvalue",
            "symbol",
            "symbol2",
            "numvalue2",
          ];
          fields.forEach((field) => {
            if (rule.busWaterWarnruleConditionsList[i][field] === undefined) {
              this.$set(rule.busWaterWarnruleConditionsList[i], field, "");
            }
          });
        }
      }
      return true;
    },

    // 符号值转文本
    getSymbolText(symbol) {
      return this.symbolMap[symbol] || "";
    },

    // 判断是否有第二个条件
    hasSecondCondition(condition) {
      return !!condition.symbol2 || !!condition.numvalue2;
    },

    // 更新单个规则
    updateRule(ruleIndex) {
      const rule = this.warnRules[ruleIndex];
      if (!rule.id) {
        this.$message.error("规则ID不存在，无法更新");
        return;
      }

      // 深拷贝原始数据，保留所有字段
      const updateData = JSON.parse(JSON.stringify(rule));
      // 更新时间
      const now = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
      updateData.updatetime = now;

      // 同步条件列表中的更新时间
      updateData.busWaterWarnruleConditionsList.forEach((condition) => {
        condition.updatetime = now;
      });

      console.log(">>>更新的数据", updateData);

      // 调用更新接口
      updateWarningRule(updateData)
        .then((res) => {
          this.$message.success("更新成功");
          this.getWarningRule();
        })
        .catch((err) => {
          console.error("更新失败:", err);
          this.$message.error("更新失败，请重试");
        });
    },
  },
};
</script>

<style scoped>
.warn-rule-container {
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: space-around;
}
.warn-rule-item {
  width: 30%;
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.warn-form {
  width: 100%;
}
.judgment-condition {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}
/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .warn-rule-item {
    width: 48%;
  }
}
@media screen and (max-width: 768px) {
  .warn-rule-item {
    width: 100%;
  }
}
</style>
